/**
 * 配音管理相关API接口
 */

import type { ApiResponse, PageResult } from './types/common'

import type {
  RecordingStatsRespVO,
  UserRecordingAggregateRespVO,
  UserRecordingCreateReqVO,
  UserRecordingDetailPageRespVO,
  UserRecordingDetailRespVO,
  UserRecordingListParams,
  UserRecordingPublicSettingReqVO,
  UserRecordingRespVO,
  UserRecordingShareRespVO,
} from './types/recording'
import { http } from '@/utils/request'

/**
 * 获取用户配音列表
 */
export function getUserRecordingList(params: UserRecordingListParams) {
  return http.get<ApiResponse<PageResult<UserRecordingRespVO>>>('/reading/user-recordings', {
    page: params.pageNo,
    limit: params.pageSize,
  })
}

/**
 * 获取用户配音聚合列表（按绘本聚合）
 */
export function getUserRecordingAggregateList(params: { pageNo: number, pageSize: number }) {
  return http.get<ApiResponse<PageResult<UserRecordingAggregateRespVO>>>('/reading/user-recordings/aggregate', {
    page: params.pageNo,
    limit: params.pageSize,
  })
}

/**
 * 获取用户配音详情页信息
 */
export function getUserRecordingDetailPage(bookId: number) {
  return http.get<ApiResponse<UserRecordingDetailPageRespVO>>(`/reading/user-recordings/detail/${bookId}`)
}

/**
 * 批量设置绘本配音的公开状态
 */
export function setBookRecordingsPublic(data: UserRecordingPublicSettingReqVO) {
  return http.put<ApiResponse<boolean>>('/reading/user-recordings/public-setting', data)
}

/**
 * 生成绘本配音分享信息
 */
export function generateBookRecordingShare(bookId: number) {
  return http.post<ApiResponse<UserRecordingShareRespVO>>(`/reading/user-recordings/share/${bookId}`)
}

/**
 * 删除绘本的所有配音记录
 */
export function deleteBookRecordings(bookId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/user-recordings/book/${bookId}`)
}

/**
 * 创建配音记录
 */
export function createUserRecording(data: UserRecordingCreateReqVO) {
  return http.post<ApiResponse<number>>('/reading/recordings/create', data)
}

/**
 * 获取配音记录详情
 */
export function getUserRecordingDetail(recordingId: number) {
  return http.get<ApiResponse<UserRecordingDetailRespVO>>(`/reading/recordings/${recordingId}`)
}

/**
 * 更新配音记录
 */
export function updateUserRecording(recordingId: number, data: {
  title?: string
  description?: string
  isPublic?: boolean
}) {
  return http.put<ApiResponse<boolean>>(`/reading/recordings/${recordingId}`, data)
}

/**
 * 删除配音记录
 */
export function deleteUserRecording(recordingId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/user-recordings/${recordingId}`)
}

/**
 * 获取绘本的配音记录
 */
export function getBookRecordings(bookId: number) {
  return http.get<ApiResponse<UserRecordingRespVO[]>>(`/reading/recordings/book/${bookId}`)
}

/**
 * 获取页面的配音记录
 */
export function getPageRecordings(pageId: number) {
  return http.get<ApiResponse<UserRecordingRespVO[]>>(`/reading/recordings/page/${pageId}`)
}

/**
 * 获取公开的配音记录
 */
export function getPublicRecordings(params: UserRecordingListParams) {
  return http.get<ApiResponse<PageResult<UserRecordingRespVO>>>('/reading/recordings/public', params)
}

/**
 * 播放配音记录
 */
export function playUserRecording(recordingId: number) {
  return http.post<ApiResponse<boolean>>(`/reading/recordings/${recordingId}/play`)
}

/**
 * 点赞配音记录
 */
export function likeUserRecording(recordingId: number) {
  return http.post<ApiResponse<boolean>>(`/reading/recordings/${recordingId}/like`)
}

/**
 * 取消点赞配音记录
 */
export function unlikeUserRecording(recordingId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/recordings/${recordingId}/like`)
}

/**
 * 分享配音记录
 */
export function shareUserRecording(recordingId: number) {
  return http.post<ApiResponse<boolean>>(`/reading/user-recordings/${recordingId}/share`)
}

/**
 * 获取配音统计
 */
export function getRecordingStats() {
  return http.get<ApiResponse<RecordingStatsRespVO>>('/reading/recordings/stats')
}

/**
 * 上传配音文件
 */
export function uploadRecordingFile(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<ApiResponse<string>>('/reading/recordings/upload', formData, {
    'Content-Type': 'multipart/form-data',
  })
}

/**
 * 保存用户录制音频（页面级别）
 */
export function saveUserRecording(data: {
  bookId: number
  pageNumber: number
  audioUrl: string
  duration: number
}) {
  return http.post<ApiResponse<boolean>>('/reading/recordings', data)
}

/**
 * 获取用户录制音频（页面级别）
 */
export function getUserRecordingByPage(pageId: number) {
  return http.get<ApiResponse<UserRecordingDetailRespVO>>(`/reading/recordings/page/${pageId}`)
}

/**
 * 批量删除配音记录
 */
export function batchDeleteRecordings(recordingIds: number[]) {
  return http.delete<ApiResponse<boolean>>('/reading/recordings/batch-delete', { recordingIds })
}

/**
 * 获取配音记录数量
 */
export function getRecordingCount() {
  return http.get<ApiResponse<number>>('/reading/recordings/count')
}

/**
 * 检查配音记录是否存在
 */
export function checkRecordingExists(bookId: number, pageNumber: number) {
  return http.get<ApiResponse<boolean>>('/reading/recordings/check', { bookId, pageNumber })
}

/**
 * 检查页面是否已有录音
 */
export function checkExistingRecording(bookId: number, pageNumber: number) {
  return http.get<ApiResponse<boolean>>('/reading/recordings/check-existing', {
    bookId,
    pageNumber,
  })
}

/**
 * 上传录音文件（支持覆盖）- 使用符合文档规范的接口
 */
export function uploadRecording(params: {
  bookId: number
  pageId: number
  pageNumber: number
  file: any
  duration: number
  quality?: string
}) {
  return new Promise((resolve, reject) => {
    const formData = {
      bookId: params.bookId.toString(),
      pageId: params.pageId.toString(),
      pageNumber: params.pageNumber.toString(),
      duration: params.duration.toString(),
      quality: params.quality || 'medium',
    }

    uni.uploadFile({
      url: '/reading/recordings/upload', // 使用相对路径，让拦截器处理
      filePath: params.file,
      name: 'file',
      formData,
      success: (res) => {
        console.log('📥 录音上传响应详情:', {
          statusCode: res.statusCode,
          header: res.header,
          dataType: typeof res.data,
          dataLength: res.data ? res.data.length : 0,
          dataPreview: res.data ? res.data.substring(0, 200) : 'null'
        })

        try {
          // 检查响应状态码
          if (res.statusCode !== 200) {
            reject(new Error(`服务器响应错误: HTTP ${res.statusCode}`))
            return
          }

          // 检查响应数据是否存在
          if (!res.data) {
            reject(new Error('服务器返回空响应'))
            return
          }

          // 尝试解析JSON
          const data = JSON.parse(res.data)
          console.log('✅ JSON解析成功:', data)

          if (data.code === 0) {
            resolve(data.data)
          } else {
            reject(new Error(data.msg || '上传失败'))
          }
        } catch (error) {
          console.error('❌ JSON解析失败:', error)
          console.error('原始响应数据:', res.data)
          reject(new Error(`响应解析失败: ${error.message}. 响应内容: ${res.data ? res.data.substring(0, 500) : 'null'}`))
        }
      },
      fail: (error) => {
        reject(error)
      },
    })
  })
}
